﻿using System.Security.Authentication;
using System.Security.Claims;
using DevProtocolApi.Dtos.system;
using Infrastructure.Helper;
using Infrastructure.Model;
using Infrastructure.Model.UserAuth;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Distributed;
using Newtonsoft.Json;
using Service.IService;

namespace DevProtocolApi.Controllers.sysControllers
{
    
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class AuthController : BaseController
    {
        private readonly IAuthService _authService;
        private readonly IDistributedCache _cache;
        private readonly ILogger<AuthController> _logger;

        public AuthController(
            IAuthService authService,
            IDistributedCache cache,
            ILogger<AuthController> logger)
        {
            _authService = authService;
            _cache = cache;
            _logger = logger;
        }

        /// <summary>
        /// 用户登录接口
        /// </summary>
        /// <param name="request">登录请求参数</param>
        /// <returns>包含JWT令牌的响应</returns>
        [AllowAnonymous]
        [HttpPost]
        public async Task<IActionResult> Login([FromBody] LoginRequest request)
        {
            // 1. 参数验证
            if (!ModelState.IsValid)
                return Failed("用户名或密码格式错误");

            try
            {
                // 2. 认证核心逻辑
                 var authResult = await _authService.AuthenticateAsync(request.userName, request.password);
                if (!authResult.Success)
                    return Unauthorized(authResult.Message);

                // 3. 构建用户完整上下文
                var loginUser = new LoginUser(
                    userId: authResult.UserId,
                    userName: authResult.UserName,
                    dept: authResult.DeptCode,
                    roleIds: authResult.GroupIds ?? new List<string>(),
                    permissions: new List<string> { "test","Add"},
                    locations: new List<string>(),
                    deptLocations: new List<UserDeptLocation>(),
                    groupDetails: new List<GroupDetail>()
                );

                // 4. 生成JWT令牌
                var claims = new List<Claim>{
                    new Claim(ClaimTypes.NameIdentifier, loginUser.UserId),
                    new Claim(ClaimTypes.Name, loginUser.UserName),
                    new Claim("DeptCode", loginUser.Dept ?? string.Empty),
                    new Claim(ClaimTypes.UserData, JsonConvert.SerializeObject(loginUser)),
};
                // 添加权限Claims
                foreach (var permission in loginUser.Permissions)
                {
                    claims.Add(new Claim("Permission", permission));
                }

                var token = JwtUtil.GenerateJwtToken(claims);

             
                // 6. 返回标准化响应
                return Success(new LoginResponse
                {
                    Token = token,
                    UserInfo = new UserInfoDto
                    {
                        UserId = loginUser.UserId,
                        UserName = loginUser.UserName,
                        Dept = loginUser.Dept??"技术部",
                        Roles = loginUser.GroupIds
                    },
                    TokenExpiry = DateTime.UtcNow.AddHours(4),
                    NeedChangePassword = authResult.NeedChangePassword
                });
            }
            catch (AuthenticationException ex)
            {
                _logger.LogWarning(ex, "用户认证失败: {Username}", request.userName);
                return Unauthorized(ex.Message);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "登录系统异常: {Username}", request.userName);
                return Failed("系统繁忙，请稍后重试");
            }
        }
        [HttpPost]
        public async Task<IActionResult> ChangePassword([FromBody] ChangePasswordDto dto)
        {
            try
            {
                var success = await _authService.ChangePasswordAsync(dto.UserId, dto.OldPassword, dto.NewPassword);
                return success ? Success("密码修改成功") : Failed("密码修改失败");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"修改密码失败: {dto.UserId}");
                return Failed(ex.Message);
            }
        }

        [HttpPost]
        public async Task<IActionResult> ResetPassword([FromBody] ResetPasswordDto dto)
        {
            try
            {
                var success = await _authService.ResetPasswordAsync(dto.UserId, dto.NewPassword);
                return success ? Success("密码重置成功") : Failed("密码重置失败");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"重置密码失败: {dto.UserId}");
                return Failed(ex.Message);
            }
        }
    }

  
}

